<!--new-->
<!--
<template>
    <div class="admin-page">
        <div class="page-header">
            <div class="table-header">
                <div class="table-actions">
                    <el-button type="primary" @click="handleAddAdmin" size="small" icon="el-icon-plus">添加商品
                    </el-button>
                </div>
            </div>

            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center; ">
                        <span>商品名称:</span>
                        <el-input v-model="form.search" size="small" style="width: 70%;margin-left: 10px;"></el-input>
                    </div>
                    <div style="display: flex; align-items: center; ">
                        <span>状态:</span>
                        <el-select v-model="form.state" placeholder="请选择" style="width: 70%;margin-left: 10px;"
                                   size="small">
                            <el-option
                                v-for="item in statusList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="mini" @click="toSearch">搜索</el-button>
                    <el-button type="success" size="mini" @click="reset">重置</el-button>
                </div>
            </div>
            <el-table height="560" :data="adminList" border style="width: 100%;overflow-y: auto">
                :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="id" align="center" label="ID" width="80"/>
                <el-table-column prop="title" label="商品标题" align="center"
                                 show-overflow-tooltip></el-table-column>
                <el-table-column label="默认" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.type === 1 ? '复购商品' : (scope.row.type === 2 ? '特殊商品' : (scope.row.type === 3 ? '积分商品' : '未知类型')) }}
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="f_thumb" label="产品封面" width="80">
                    <template slot-scope="scope">
                        <img style="width: 50px;height: 50px" :src="$appConfig.imgPath + scope.row.f_thumb"/>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="80" label="商品状态">
                    <template slot-scope="scope">
                        {{ scope.row.state === 1 ? '正常' : scope.row.state === 0 ? '下架' : '删除' }}
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="sort" width="80" label="商品排序"/>
                <el-table-column align="center" prop="pur_price" label="采购价"/>
                <el-table-column align="center" prop="price" label="销售价"/>
                <el-table-column align="center" prop="num" width="80" label="商品数量"/>
                <el-table-column align="center" label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑
                        </el-button>
                        <el-button type="text" size="small" @click="handleDelete(scope.row)" icon="el-icon-delete"
                                   class="delete-btn">删除
                        </el-button>
                        <el-button type="success" size="small" @click="handleStateChange(scope.row)"
                                   :style="{ backgroundColor: scope.row.state === 0? 'red' : '#67c23a' }">
                            {{ scope.row.state === 0 ? '下架' : '上架' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                           layout="total,  pager, next, jumper" :total="total"/>
            &lt;!&ndash; 添加商品对话框 &ndash;&gt;
            <el-dialog title="添加商品" :visible.sync="addDialogVisible" width="50%" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="标题" prop="title">
                        <el-input style="width: 90%;" v-model="adminForm.title"/>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="clas_id">
                        <el-cascader
                            v-model="adminForm.clas_id"
                            :options="categoryList"
                            :props="{
                                value: 'id',
                                label: 'name',
                                children: 'children',
                                emitPath: false,
                                checkStrictly: true
                            }"
                            clearable
                            placeholder="请选择"
                            size="small"
                            style="width: 90%;"
                        />
                    </el-form-item>
                    <el-form-item label="商品简介" prop="description">
                        <el-input style="width: 90%;" v-model="adminForm.description"/>
                    </el-form-item>
                    <el-form-item label="分类类型">
                        <el-radio-group v-model="adminForm.type">
                            <el-radio :label="1">复购商品</el-radio>
                            <el-radio :label="2">特殊商品</el-radio>
                            <el-radio :label="3">积分商品</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="推荐">
                        <el-radio-group v-model="adminForm.is_recommend">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="商品状态">
                        <el-radio-group v-model="adminForm.state">
                            <el-radio :label="1">正常</el-radio>
                            <el-radio :label="0">下架</el-radio>
                            <el-radio :label="-1">删除</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品排序" prop="sort">
                        <el-input style="width: 90%;" v-model="adminForm.sort"/>
                    </el-form-item>
                    <el-form-item label="采购价" prop="pur_price">
                        <el-input style="width: 90%;" v-model="adminForm.pur_price"/>
                    </el-form-item>
                    <el-form-item label="销售价" prop="price">
                        <el-input style="width: 90%;" v-model="adminForm.price"/>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="num">
                        <el-input style="width: 90%;" v-model="adminForm.num"/>
                    </el-form-item>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="中级服务商：">
                                    <el-input v-model="adminForm.rebate.intermediate" placeholder="请输入金额" style="width: 100px;"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="高级服务商：">
                                    <el-input v-model="adminForm.rebate.senior" placeholder="请输入金额" style="width: 100px"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="区域服务商：">
                                    <el-input v-model="adminForm.rebate.region" placeholder="请输入金额" style="width: 100px"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="城市服务商：">
                                <el-input v-model="adminForm.rebate.city" placeholder="请输入金额" style="width: 100px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="大区服务商：">
                                <el-input v-model="adminForm.rebate.regions" placeholder="请输入金额" style="width: 100px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="全球服务商：">
                                <el-input v-model="adminForm.rebate.global" placeholder="请输入金额" style="width: 100px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="封面图" prop="thumb">
                        <el-upload
                            :key="'cover-upload-' + adminForm.f_thumb"
                            class="avatar-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            :show-file-list="false"
                            :on-success="handleCoverSuccess"
                            :before-upload="beforeCoverUpload">
                            <img v-if="adminForm.f_thumb" :src="$appConfig.imgPath + adminForm.f_thumb"
                                 class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品详情图" prop="thumb">
                        <el-upload
                            class="detail-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            list-type="picture-card"
                            :file-list="detailImages"
                            :on-success="handleDetailSuccess"
                            :before-upload="beforeDetailUpload"
                            :on-remove="handleRemove"
                            :on-preview="handlePreview"
                            :key="'detail-upload-' + detailImages.length"
                            multiple>
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品描述">
                        <div v-if="addDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="addEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleAddEditorCreated"
                            />
                        </div>
                        <div v-if="editDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleEditEditorCreated"
                            />
                        </div>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false" size="small">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="small">确定</el-button>
                </div>
            </el-dialog>
            &lt;!&ndash; 编辑商品对话框 &ndash;&gt;
            <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="50%" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="标题" prop="title">
                        <el-input style="width: 90%;" v-model="adminForm.title"/>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="clas_id">
                        <el-cascader
                            v-model="adminForm.clas_id"
                            :options="categoryList"
                            :props="{
                                value: 'id',
                                label: 'name',
                                children: 'children',
                                emitPath: false,
                                checkStrictly: true
                            }"
                            clearable
                            placeholder="请选择"
                            size="small"
                            style="width: 90%;"
                        />
                    </el-form-item>
                    <el-form-item label="商品简介" prop="description">
                        <el-input style="width: 90%;" v-model="adminForm.description"/>
                    </el-form-item>
                    <el-form-item label="分类类型">
                        <el-radio-group v-model="adminForm.type">
                            <el-radio :label="1">复购商品</el-radio>
                            <el-radio :label="2">特殊商品</el-radio>
                            <el-radio :label="3">积分商品</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="推荐">
                        <el-radio-group v-model="adminForm.is_recommend">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="商品状态">
                        <el-radio-group v-model="adminForm.state">
                            <el-radio :label="1">正常</el-radio>
                            <el-radio :label="0">下架</el-radio>
                            <el-radio :label="-1">删除</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品排序" prop="sort">
                        <el-input style="width: 90%;" v-model="adminForm.sort"/>
                    </el-form-item>
                    <el-form-item label="采购价" prop="pur_price">
                        <el-input style="width: 90%;" v-model="adminForm.pur_price"/>
                    </el-form-item>
                    <el-form-item label="销售价" prop="price">
                        <el-input style="width: 90%;" v-model="adminForm.price"/>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="num">
                        <el-input style="width: 90%;" v-model="adminForm.num"/>
                    </el-form-item>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="中级服务商：">
                                <el-input v-model="adminForm.rebate.intermediate" placeholder="请输入金额" style="width: 100px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="高级服务商：">
                                <el-input v-model="adminForm.rebate.senior" placeholder="请输入金额" style="width: 100px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="区域服务商：">
                                <el-input v-model="adminForm.rebate.region" placeholder="请输入金额" style="width: 100px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="城市服务商：">
                                <el-input v-model="adminForm.rebate.city" placeholder="请输入金额" style="width: 100px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="大区服务商：">
                                <el-input v-model="adminForm.rebate.regions" placeholder="请输入金额" style="width: 100px;"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="全球服务商：">
                                <el-input v-model="adminForm.rebate.global" placeholder="请输入金额" style="width: 100px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="封面图" prop="thumb">
                        <el-upload
                            :key="'cover-upload-' + adminForm.f_thumb"
                            class="avatar-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            :show-file-list="false"
                            :on-success="handleCoverSuccess"
                            :before-upload="beforeCoverUpload">
                            <img v-if="adminForm.f_thumb" :src="$appConfig.imgPath + adminForm.f_thumb"
                                 class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品详情图" prop="thumb">
                        <el-upload
                            class="detail-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            list-type="picture-card"
                            :file-list="detailImages"
                            :on-success="handleDetailSuccess"
                            :before-upload="beforeDetailUpload"
                            :on-remove="handleRemove"
                            :on-preview="handlePreview"
                            :key="'detail-upload-' + detailImages.length"
                            multiple>
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品描述">
                        <div v-if="addDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="addEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleAddEditorCreated"
                            />
                        </div>
                        <div v-if="editDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleEditEditorCreated"
                            />
                        </div>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false" size="small">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="small">确定</el-button>
                </div>
            </el-dialog>

            &lt;!&ndash; 图片预览弹窗 &ndash;&gt;
            <el-dialog :visible.sync="previewVisible" append-to-body class="preview-dialog"
                       :close-on-click-modal="true">
                <img :src="previewImage" alt="预览图片" class="preview-image">
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {mapState} from "vuex";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
// 引入编辑器样式
import '@wangeditor/editor/dist/css/style.css'

export default {
    components: {
        Editor,
        Toolbar
    },
    data() {
        return {
            adminList: [],
            addEditor: null,   // 添加对话框编辑器实例
            editEditor: null,  // 编辑对话框编辑器实例
            currentPage: 1,
            pageSize: 25,
            total: 0,
            detailImages: [],
            token: "",
            previewImage: '', // 用于存储预览图片的 URL
            previewVisible: false, // 用于控制图片预览弹窗的显示隐藏
            form: {
                search: "",
                clas_id: "",
                state: "",
            },
            addDialogVisible: false,
            editDialogVisible: false,
            adminForm: {
                is_recommend:1,
                title: '',
                clas_id: [],
                type: 1,
                description: '',
                thumb: '',
                f_thumb: '',
                rebat_money: '',
                content: '',
                state: 1,
                sort: '',
                pur_price: '',
                price: '',
                num: '',
                rebate:{
                    primary: '',
                    intermediate: '',
                    senior: '',
                    region: '',
                    city: '',
                    regions: '',
                    global: '',
                }

            },
            adminRules: {
                title: [{required: true, message: '请输入商品标题', trigger: 'blur'}],
                clas_id: [{required: true, message: '请输入商品分类', trigger: 'blur'}],
                type: [{required: true, message: '请选择商品类型', trigger: 'change'}],
                description: [{required: true, message: '请输入商品描述', trigger: 'blur'}],
                thumb: [{required: true, message: '请输入图片', trigger: 'blur'}],
                content: [{required: true, message: '请输入商品描述', trigger: 'blur'}],
                state: [{required: true, message: '请选择商品状态', trigger: 'change'}],
                sort: [{required: true, message: '请输入商品排序', trigger: 'blur'}],
                pur_price: [{required: true, message: '请输入采购价', trigger: 'blur'}],
                price: [{required: true, message: '请输入销售价', trigger: 'blur'}],
                num: [{required: true, message: '请输入商品数量', trigger: 'blur'}],
                admin_id: [{required: true, message: '请输入添加人', trigger: 'blur'}],
            },
            categoryList: [],
            statusList: [
                {
                    id: 1,
                    name: "上架"
                }, {
                    id: 0, name: '下架'
                }

            ],
            imageUrl: '',
            imageUrl1: '',

        };
    },
    mounted() {
        this.fetchAdminList();
        this.getCategory();
    },
    computed: {
        ...mapState(["userInfo"]),
        dynamicEditorConfig() {
            const userInfo = localStorage.getItem("userInfo");
            let token = '';
            if (userInfo) {
                try {
                    const parsedUserInfo = JSON.parse(userInfo);
                    token = parsedUserInfo.token || '';
                    // Assign to data property if needed elsewhere, though computed should be sufficient
                    this.token = token;
                } catch (e) {
                    console.error("Failed to parse userInfo from localStorage", e);
                }
            }
            return {
                placeholder: '请输入商品描述...',
                MENU_CONF: {
                    uploadImage: {
                        server: '/admin/shop/imgUpload', // Using proxy path
                        fieldName: 'file',
                        headers: {
                            // Ensure the header name matches what the backend expects (e.g., Authorization or token)
                            token: token // Using 'token' as per previous config, adjust if backend expects 'Authorization'
                        },
                        // Custom insert logic
                        customInsert(res, insertFn) {
                            // res is the server response {state, code, msg, data: [...]}
                            if (res.code === 200 && res.data && res.data.length > 0) {
                                const relativeUrl = res.data[0];
                                // IMPORTANT: Construct the FULL URL for the image src
                                const fullUrl = (window.$appConfig ? window.$appConfig.imgPath : '') + relativeUrl;
                                // insertFn(url, alt, href)
                                insertFn(fullUrl, 'image', fullUrl); // Insert image with alt text and optional link
                            } else {
                                // Handle upload failure reported by the server
                                // You might want to use this.$message or similar here
                                console.error('Server reported upload error:', res.msg);
                                alert(`图片上传失败: ${res.msg}`); // Simple alert, replace with Element UI message if preferred
                            }
                        },
                        // Optional: Add more specific error handlers if needed
                        // onError(file, err, res) {
                        //    console.error('Upload network/config error', err);
                        //    alert(`图片上传出错: ${err.message}`);
                        // },
                        // onFailed(file, res) {
                        //     // This might overlap with customInsert's failure case depending on wangEditor version
                        //     console.error('Upload failed (onFailed)', res);
                        // }
                    },
                    codeSelectLang: [
                        { text: 'JavaScript', value: 'javascript' },
                        { text: 'HTML', value: 'html' },
                        { text: 'CSS', value: 'css' },
                        { text: 'Java', value: 'java' },
                        { text: 'Python', value: 'python' },
                        { text: 'C', value: 'c' },
                        { text: 'C++', value: 'cpp' },
                        { text: 'C#', value: 'csharp' },
                        { text: 'PHP', value: 'php' },
                        { text: 'Go', value: 'go' },
                        { text: 'Ruby', value: 'ruby' },
                        { text: 'Markdown', value: 'markdown' }
                    ]
                }
            };
        }
    },
    beforeDestroy() {
        this.handleDialogClose()
    },
    methods: {
        handleEditEditorCreated(editor) {
            this.editEditor = editor;
            if (this.adminForm.content) {
                editor.setHtml(this.adminForm.content);
            }
        },
        handleAddEditorCreated(editor) {
            this.addEditor = editor;
        },
        // 对话框关闭时销毁编辑器
        handleDialogClose() {
            // 销毁编辑器实例
            if (this.addEditor) {
                this.addEditor.destroy();
                this.addEditor = null;
            }
            if (this.editEditor) {
                this.editEditor.destroy();
                this.editEditor = null;
            }

            // 保留图片数据
            this.detailImages = [];
        },
        getProductDetail(id) {
            return this.$http.get(`/admin/shop/edit`, {params: {id}}).then(result => {
                if (result.code === 200) {
                    return result.data;
                } else {
                    this.$message.error(result.msg);
                    return null;
                }
            });
        },
        handleCoverSuccess(res, file) {
            if (res.code === 200 && res.data) {
                try {
                    const imgPath = res.data;
                    this.adminForm.f_thumb = Array.isArray(imgPath) ? imgPath.join('') : imgPath;
                    this.$nextTick(() => {
                        this.$forceUpdate();
                    });
                    this.$message.success({
                        message: '封面图上传成功',
                        type: 'success',
                        duration: 1500
                    });
                } catch (error) {
                    console.error('处理封面图上传响应失败:', error);
                    this.$message.error('处理封面图数据失败');
                }
            } else {
                this.$message.error(res.msg || '封面图上传失败');
            }
        },
        beforeCoverUpload(file) {
            const isValidFormat = ['image/jpeg', 'image/png'].includes(file.type);
            const isLt20M = file.size / 1024 / 1024 < 20;

            if (!isValidFormat) {
                this.$message.error('封面图只能是 JPG/PNG 格式!');
                return false;
            }
            if (!isLt20M) {
                this.$message.error('封面图大小不能超过 20MB!');
                return false;
            }
            return true;
        },
        handleDetailSuccess(res, file) {
            if (res.code === 200 && res.data) {
                try {
                    const imgPath = res.data; // 获取相对路径
                    const currentImages = this.adminForm.thumb ? this.adminForm.thumb.split(',') : [];

                    if (!currentImages.includes(imgPath)) {
                        currentImages.push(imgPath);
                        this.adminForm.thumb = currentImages.join(',');
                        this.detailImages = currentImages.map(url => ({
                            url: this.$appConfig.imgPath + url,
                            name: url.split('/').pop() || 'detail_image'
                        }));
                    }
                    this.$message.success({
                        message: '详情图上传成功',
                        type: 'success',
                        duration: 1500
                    });
                } catch (error) {
                    console.error('处理详情图上传响应失败:', error);
                }
            } else {
                this.$message.error(res.msg || '详情图上传失败');
            }
        },
        beforeDetailUpload(file) {
            const isValidFormat = ['image/jpeg', 'image/png'].includes(file.type);
            const isLt20M = file.size / 1024 / 1024 < 20;

            if (!isValidFormat) {
                this.$message.error('详情图只能是 JPG/PNG 格式!');
                return false;
            }
            if (!isLt20M) {
                this.$message.error('详情图大小不能超过 20MB!');
                return false;
            }
            return true;
        },
        handleRemove(file) {
            try {
                // 获取当前保存的相对路径数组
                const currentImages = this.adminForm.thumb ? this.adminForm.thumb.split(',').filter(url => url.trim()) : [];

                // 确定要删除的相对路径
                let deleteUrl = '';
                if (file.response && file.response.data) { // 新上传的图片
                    deleteUrl = file.response.data;
                } else { // 已存在的图片
                    deleteUrl = file.url.replace(this.$appConfig.imgPath, '');
                }

                // 过滤出保留的图片
                const updatedImages = currentImages.filter(url => url !== deleteUrl);

                // 更新表单数据和显示列表
                this.adminForm.thumb = updatedImages.join(',');
                this.detailImages = updatedImages.map(url => ({
                    url: this.$appConfig.imgPath + url,
                    name: url.split('/').pop() || 'detail_image'
                }));

                this.$message.success({
                    message: '图片已删除',
                    type: 'success',
                    duration: 1500
                });
            } catch (error) {
                console.error('删除图片失败:', error);
                this.$message.error('删除图片失败，请重试');
            }
        },

        handlePreview(file) {
            this.previewImage = file.url;
            this.previewVisible = true;
        },
        getCategory() {
            this.$http.get('/admin/clas/lists', {limit: 1}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.categoryList = newListData;
                    this.total = result.data.total || newListData.length;
                }
            });
        },
        fetchAdminList() {
            const params = {
                page: this.currentPage,
                limit: this.pageSize
            };
            this.$http.get('/admin/shop/lists', {params}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                }
            });
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchAdminList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList();
        },
        handleAddAdmin() {
            this.adminForm = {
                rebate:{
                    primary: '',
                    intermediate: '',
                    senior: '',
                    region: '',
                    city: '',
                    regions: '',
                    global: '',
                },
                is_recommend:1,
                title: '',
                clas_id: [],
                type: 1,
                description: '',
                thumb: '',
                f_thumb: '',
                content: '',
                state: 1,
                sort: '',
                pur_price: '',
                price: '',
                num: '',
                admin_id: '',
            };
            this.detailImages = []
            this.$refs.adminForm && this.$refs.adminForm.clearValidate();
            this.addDialogVisible = true;
            this.$nextTick(() => {
                if (this.editor) {
                    this.editor.setHtml('');
                }
            });
        },
        async handleEdit(row) {
            try {
                this.$message.info({
                    message: '正在加载商品信息...',
                    duration: 1000
                });

                const data = await this.getProductDetail(row.id);
                console.log('编辑商品返回数据:', data); // 加这一行
                if (data) {
                    // 处理图片数据
                    const thumbArray = (data.thumb || '').split(',').filter(url => url.trim());
                    this.detailImages = thumbArray.map(url => ({
                        url: this.$appConfig.imgPath + url, // 显示用完整URL
                        name: url.split('/').pop() || 'detail_image'
                    }));

                    // 处理分类回显：找到分类路径
                    let clasPath = this.findCategoryPath(this.categoryList, data.clas_id);
                    this.adminForm = {
                        ...data,
                        f_thumb: data.f_thumb || '',
                        thumb: data.thumb || '',
                        clas_id: clasPath.length ? clasPath : data.clas_id, // 兼容老数据
                        rebate: {
                            primary: '',
                            intermediate: '',
                            senior: '',
                            region: '',
                            city: '',
                            regions: '',
                            global: '',
                            ...(data.rebate || {})
                        }
                    };

                    this.$refs.adminForm && this.$refs.adminForm.clearValidate();
                    this.editDialogVisible = true;
                } else {
                    this.$message.error('未获取到商品数据');
                }
            } catch (error) {
                console.error('加载商品详情失败:', error);
                this.$message.error('加载商品详情失败，请重试');
            }
        },
        toSearch() {
            this.$http.get('/admin/shop/lists', {params: this.form, limit: 1}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        reset() {
            this.form = {}
            this.fetchAdminList()
        },
        handleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            this.$http.post('/admin/shop/del', {
                title: row.title,
                clas_id: row.clas_id,
                type: row.type,
                description: row.description,
                thumb: row.thumb,
                content: row.content,
                sort: row.sort,
                pur_price: row.pur_price,
                price: row.price,
                num: row.num,
                admin_id: row.admin_id,
                id: row.id,
                state: newState
            }).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },
        handleDelete(data) {
            this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message.info({
                    message: '正在删除...',
                    duration: 0,
                    showClose: true,
                    iconClass: 'el-icon-loading'
                });

                // 用户点击了确定按钮
                this.$http.post('/admin/shop/del', {
                    id: data.id,
                    state: "-1"
                }).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.fetchAdminList();
                    } else {
                        this.$message.error(result.msg);
                    }
                }).catch(error => {
                    console.error('删除商品失败:', error);
                    this.$message.error('删除商品失败，请重试');
                }).finally(() => {
                    // 关闭加载提示
                    this.$message.closeAll();
                });
            }).catch(() => {
                // 用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        submitForm() {
            this.$refs.adminForm.validate(valid => {
                if (valid) {
                    if (!this.adminForm.f_thumb) {
                        this.$message.warning('请上传商品封面图');
                        return;
                    }

                    this.$message.info({
                        message: '正在保存...',
                        duration: 0,
                        showClose: true,
                        iconClass: 'el-icon-loading'
                    });

                    // 只取最后一级分类id
                    let submitData = {
                        ...this.adminForm,
                        clas_id: Array.isArray(this.adminForm.clas_id) ? this.adminForm.clas_id[this.adminForm.clas_id.length - 1] : this.adminForm.clas_id
                    };

                    this.$http.post('/admin/shop/edit', submitData).then(result => {
                        if (result.code === 200) {
                            this.$message.success({
                                message: result.msg,
                                type: 'success',
                                duration: 1500
                            });
                            this.addDialogVisible = false;
                            this.editDialogVisible = false;
                            this.fetchAdminList();
                        } else {
                            this.$message.error(result.msg);
                        }
                    }).catch(error => {
                        console.error('保存商品失败:', error);
                        this.$message.error('保存商品失败，请重试');
                    }).finally(() => {
                        // 关闭加载提示
                        this.$message.closeAll();
                    });
                }
            });
        },
        // 递归查找分类路径
        findCategoryPath(list, id, path = []) {
            for (let item of list) {
                if (item.id === id) {
                    return [...path, item.id];
                }
                if (item.children && item.children.length) {
                    const found = this.findCategoryPath(item.children, id, [...path, item.id]);
                    if (found.length) return found;
                }
            }
            return [];
        },
    }
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
    box-shadow: 0 0 8px rgba(64, 158, 255, 0.4);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    transition: all 0.3s;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
    border-radius: 6px;
}

/* 详情图上传样式 */
.detail-uploader /deep/ .el-upload&#45;&#45;picture-card {
    transition: all 0.3s;

    &:hover {
        border-color: #409EFF;
        box-shadow: 0 0 8px rgba(64, 158, 255, 0.4);
    }
}

.detail-uploader /deep/ .el-upload-list&#45;&#45;picture-card .el-upload-list__item {
    transition: all 0.3s;

    &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
}

/* 预览图片样式 */
.preview-dialog {
    /deep/ .el-dialog__body {
        padding: 10px;
        text-align: center;
    }

    .preview-image {
        max-width: 100%;
        max-height: 70vh;
    }
}

.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #f0f2f5;

        .header-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
    }

    .table-header {
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
        }

        .table-actions {
            .el-button {
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }

    .el-tabs {
        margin-top: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 28px;
            border-bottom: 2px solid #f0f2f5;
        }

        :deep(.el-tabs__item) {
            font-size: 15px;
            padding: 0 28px;
            height: 44px;
            line-height: 44px;
            transition: all 0.3s;

            &.is-active {
                color: #2563eb;
                font-weight: 500;
            }

            &:hover {
                color: #2563eb;
            }
        }

        :deep(.el-tabs__active-bar) {
            height: 2px;
            background-color: #2563eb;
            transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        }
    }

    .el-table {
        margin-top: 12px;
        border-radius: 8px;
        overflow: hidden;

        :deep(th) {
            background-color: #f9fafb !important;
            font-weight: 500;
            color: #4b5563;
        }

        :deep(td) {
            padding: 12px 0;
        }

        .delete-btn {
            color: #dc2626;
            transition: all 0.3s;

            &:hover {
                color: #ef4444;
            }
        }
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    /deep/ .el-dialog__header {
        text-align: center !important;
        padding: 16px;
    }

    .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        max-height: 90vh;
        display: flex;
        flex-direction: column;

        :deep(.el-dialog__header) {
            padding: 20px 24px !important;
            border-bottom: 1px solid #f0f2f5;
            margin: 0;

            .el-dialog__title {
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }
        }

        :deep(.el-dialog__body) {
            padding: 32px 24px;
            flex: 1;
            overflow-y: auto;

            .el-form-item {
                .el-input,
                .el-select {
                    width: 320px;
                }
            }
        }

        :deep(.el-tree) {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            padding: 10px;
        }

        :deep(.el-dialog__footer) {
            padding: 16px 24px;
            border-top: 1px solid #f0f2f5;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #374151;
        }

        :deep(.el-button) {
            padding: 8px 20px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-1px);
            }
        }
    }
}

.editor-container {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding: 5px;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 10px;
    width: 90%;
}

.ellipsis-column.el-table__cell span {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
    word-break: keep-all; /* 防止中文单词被截断 */
}

.tip-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
}

/deep/ .el-tab-pane {
    height: 650px;
    overflow-y: auto;
}

/deep/ .w-e-bar-bottom .w-e-select-list {
    bottom: initial !important;
}

</style>-->


<!--old-->

<template>
    <div class="admin-page">
        <div class="page-header">
            <div class="table-header">
                <div class="table-actions">
                    <el-button type="primary" @click="handleAddAdmin" size="small" icon="el-icon-plus">添加商品
                    </el-button>
                </div>
            </div>

            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center; ">
                        <span>商品名称:</span>
                        <el-input v-model="form.search" size="small" style="width: 70%;margin-left: 10px;"></el-input>
                    </div>
                    <div style="display: flex; align-items: center; ">
                        <span>状态:</span>
                        <el-select v-model="form.state" placeholder="请选择" style="width: 70%;margin-left: 10px;"
                                   size="small">
                            <el-option
                                v-for="item in statusList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="mini" @click="toSearch">搜索</el-button>
                    <el-button type="success" size="mini" @click="reset">重置</el-button>
                </div>
            </div>

            <el-table height="560" :data="adminList" border style="width: 100%;overflow-y: auto">
                :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="id" align="center" label="ID" width="80"/>
                <el-table-column prop="title" label="商品标题" align="center"
                                 show-overflow-tooltip></el-table-column>
                <el-table-column label="默认" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.type === 1 ? '复购商品' : (scope.row.type === 2 ? '特殊商品' : (scope.row.type === 3 ? '积分商品' : '未知类型')) }}
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="f_thumb" label="产品封面" width="80">
                    <template slot-scope="scope">
                        <img style="width: 50px;height: 50px" :src="$appConfig.imgPath + scope.row.f_thumb"/>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="80" label="商品状态">
                    <template slot-scope="scope">
                        {{ scope.row.state === 1 ? '正常' : scope.row.state === 0 ? '下架' : '删除' }}
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="sort" width="80" label="商品排序"/>
                <el-table-column align="center" prop="pur_price" label="采购价"/>
                <el-table-column align="center" prop="price" label="销售价"/>
                <el-table-column align="center" prop="num" width="80" label="商品数量"/>
                <el-table-column align="center" label="操作" width="360">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑</el-button>
                        <el-button type="text" size="small" @click="handleDelete(scope.row)" icon="el-icon-delete" class="delete-btn">删除</el-button>
                        <el-button type="success" size="small" @click="handleStateChange(scope.row)" :style="{ backgroundColor: scope.row.state === 0? 'red' : '#67c23a' }">
                            {{ scope.row.state === 0 ? '下架' : '上架' }}
                        </el-button>
                        <el-button type="warning" size="small" @click="openBonusDialog(scope.row)">分红金额</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                           layout="total,  pager, next, jumper" :total="total"/>
            <!-- 添加商品对话框 -->
            <el-dialog title="添加商品" :visible.sync="addDialogVisible" width="50%" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="标题" prop="title">
                        <el-input style="width: 90%;" v-model="adminForm.title"/>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="clas_id">
                        <el-cascader
                            v-model="adminForm.clas_id"
                            :options="categoryList"
                            :props="{
                                value: 'id',
                                label: 'name',
                                children: 'children',
                                emitPath: false,
                                checkStrictly: true
                            }"
                            clearable
                            placeholder="请选择"
                            size="small"
                            style="width: 90%;"
                        />
                    </el-form-item>
                    <el-form-item label="商品简介" prop="description">
                        <el-input style="width: 90%;" v-model="adminForm.description"/>
                    </el-form-item>
                    <el-form-item label="分类类型">
                        <el-radio-group v-model="adminForm.type">
                            <el-radio :label="1">复购商品</el-radio>
                            <el-radio :label="2">特殊商品</el-radio>
                            <el-radio :label="3">积分商品</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="推荐">
                        <el-radio-group v-model="adminForm.is_recommend">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="商品状态">
                        <el-radio-group v-model="adminForm.state">
                            <el-radio :label="1">正常</el-radio>
                            <el-radio :label="0">下架</el-radio>
                            <el-radio :label="-1">删除</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品排序" prop="sort">
                        <el-input style="width: 90%;" v-model="adminForm.sort"/>
                    </el-form-item>
                    <el-form-item label="采购价" prop="pur_price">
                        <el-input style="width: 90%;" v-model="adminForm.pur_price"/>
                    </el-form-item>
                    <el-form-item label="销售价" prop="price">
                        <el-input style="width: 90%;" v-model="adminForm.price"/>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="num">
                        <el-input style="width: 90%;" v-model="adminForm.num"/>
                    </el-form-item>
                    <el-form-item label="封面图" prop="thumb">
                        <el-upload
                            :key="'cover-upload-' + adminForm.f_thumb"
                            class="avatar-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            :show-file-list="false"
                            :on-success="handleCoverSuccess"
                            :before-upload="beforeCoverUpload">
                            <img v-if="adminForm.f_thumb" :src="$appConfig.imgPath + adminForm.f_thumb"
                                 class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品详情图" prop="thumb">
                        <el-upload
                            class="detail-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            list-type="picture-card"
                            :file-list="detailImages"
                            :on-success="handleDetailSuccess"
                            :before-upload="beforeDetailUpload"
                            :on-remove="handleRemove"
                            :on-preview="handlePreview"
                            :key="'detail-upload-' + detailImages.length"
                            multiple>
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品描述">
                        <div v-if="addDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="addEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleAddEditorCreated"
                            />
                        </div>
                        <div v-if="editDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleEditEditorCreated"
                            />
                        </div>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </el-dialog>
            <!-- 编辑商品对话框 -->
            <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="50%" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="标题" prop="title">
                        <el-input style="width: 90%;" v-model="adminForm.title"/>
                    </el-form-item>
                    <el-form-item label="商品分类" prop="clas_id">
                        <el-cascader
                            v-model="adminForm.clas_id"
                            :options="categoryList"
                            :props="{
                                value: 'id',
                                label: 'name',
                                children: 'children',
                                emitPath: false,
                                checkStrictly: true
                            }"
                            clearable
                            placeholder="请选择"
                            size="small"
                            style="width: 90%;"
                        />
                    </el-form-item>
                    <el-form-item label="商品简介" prop="description">
                        <el-input style="width: 90%;" v-model="adminForm.description"/>
                    </el-form-item>
                    <el-form-item label="分类类型">
                        <el-radio-group v-model="adminForm.type">
                            <el-radio :label="1">复购商品</el-radio>
                            <el-radio :label="2">特殊商品</el-radio>
                            <el-radio :label="3">积分商品</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="推荐">
                        <el-radio-group v-model="adminForm.is_recommend">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="商品状态">
                        <el-radio-group v-model="adminForm.state">
                            <el-radio :label="1">正常</el-radio>
                            <el-radio :label="0">下架</el-radio>
                            <el-radio :label="-1">删除</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品排序" prop="sort">
                        <el-input style="width: 90%;" v-model="adminForm.sort"/>
                    </el-form-item>
                    <el-form-item label="采购价" prop="pur_price">
                        <el-input style="width: 90%;" v-model="adminForm.pur_price"/>
                    </el-form-item>
                    <el-form-item label="销售价" prop="price">
                        <el-input style="width: 90%;" v-model="adminForm.price"/>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="num">
                        <el-input style="width: 90%;" v-model="adminForm.num"/>
                    </el-form-item>
                    <el-form-item label="封面图" prop="thumb">
                        <el-upload
                            :key="'cover-upload-' + adminForm.f_thumb"
                            class="avatar-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            :show-file-list="false"
                            :on-success="handleCoverSuccess"
                            :before-upload="beforeCoverUpload">
                            <img v-if="adminForm.f_thumb" :src="$appConfig.imgPath + adminForm.f_thumb"
                                 class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品详情图" prop="thumb">
                        <el-upload
                            class="detail-uploader"
                            action="/admin/shop/imgUpload"
                            :headers="{ token: userInfo.token }"
                            list-type="picture-card"
                            :file-list="detailImages"
                            :on-success="handleDetailSuccess"
                            :before-upload="beforeDetailUpload"
                            :on-remove="handleRemove"
                            :on-preview="handlePreview"
                            :key="'detail-upload-' + detailImages.length"
                            multiple>
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品描述">
                        <div v-if="addDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="addEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleAddEditorCreated"
                            />
                        </div>
                        <div v-if="editDialogVisible" class="editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editEditor"
                            />
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                :defaultConfig="dynamicEditorConfig"
                                @onCreated="handleEditEditorCreated"
                            />
                        </div>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </el-dialog>

            <!-- 图片预览弹窗 -->
            <el-dialog :visible.sync="previewVisible" append-to-body class="preview-dialog"
                       :close-on-click-modal="true">
                <img :src="previewImage" alt="预览图片" class="preview-image">
            </el-dialog>
            <el-dialog title="分红金额设置" :visible.sync="bonusDialogVisible" width="50%" :close-on-click-modal="false" class="bonus-dialog" @close="cancal">
                <div v-if="currentProductInfo" class="bonus-product-info" style="margin-bottom: 16px;">
                    <div>商品ID：{{ currentProductInfo.id }}</div>
                    <div>商品标题：{{ currentProductInfo.title }}</div>
                    <div>销售价：{{ currentProductInfo.price }}</div>
                </div>
                <el-form :model="bonusForm" label-width="120px" size="small">
                    <el-row :gutter="10">
                        <el-col :span="12" v-for="(item, idx) in bonusFields" :key="item.key">
                            <el-form-item :label="item.label">
                                <div style="display: flex; align-items: center;">
                                    <el-input
                                        type="number"
                                        v-model.number="bonusForm[item.key]"
                                        style="width: 60%;"
                                        :placeholder="item.placeholder"
                                        :min="0.01"
                                        @input="handleInput($event, item.key)"
                                    />
                                    <el-select
                                        v-model="bonusForm.a_type[item.key]"
                                        style="width: 30%; margin-left: 8px;"
                                        size="small"
                                    >
                                        <el-option label="金额" :value="1"></el-option>
                                        <el-option label="百分比" :value="2"></el-option>
                                    </el-select>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancal" size="small">取消</el-button>
                    <el-button type="primary" @click="submitBonus" size="small">确定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {mapState} from "vuex";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
// 引入编辑器样式
import '@wangeditor/editor/dist/css/style.css'

export default {
    components: {
        Editor,
        Toolbar
    },
    data() {
        return {
            bonusFormIds: {}, // 用于存储每个 type 的 id
            adminList: [],
            addEditor: null,   // 添加对话框编辑器实例
            editEditor: null,  // 编辑对话框编辑器实例
            currentPage: 1,
            pageSize: 25,
            total: 0,
            detailImages: [],
            token: "",
            previewImage: '', // 用于存储预览图片的 URL
            previewVisible: false, // 用于控制图片预览弹窗的显示隐藏
            form: {
                search: "",
                clas_id: "",
                state: "",
            },
            addDialogVisible: false,
            editDialogVisible: false,
            adminForm: {
                is_recommend:0,
                title: '',
                clas_id: [],
                type: 1,
                description: '',
                thumb: '',
                f_thumb: '',
                rebat_money: '',
                content: '',
                state: 1,
                sort: '',
                pur_price: '',
                price: '',
                num: '',
                rebate:{
                    primary: '',
                    intermediate: '',
                    senior: '',
                    region: '',
                    city: '',
                    regions: '',
                    global: '',
                }

            },
            adminRules: {
                title: [{required: true, message: '请输入商品标题', trigger: 'blur'}],
                clas_id: [{required: true, message: '请输入商品分类', trigger: 'blur'}],
                type: [{required: true, message: '请选择商品类型', trigger: 'change'}],
                description: [{required: true, message: '请输入商品描述', trigger: 'blur'}],
                thumb: [{required: true, message: '请输入图片', trigger: 'blur'}],
                content: [{required: true, message: '请输入商品描述', trigger: 'blur'}],
                state: [{required: true, message: '请选择商品状态', trigger: 'change'}],
                sort: [{required: true, message: '请输入商品排序', trigger: 'blur'}],
                pur_price: [{required: true, message: '请输入采购价', trigger: 'blur'}],
                price: [{required: true, message: '请输入销售价', trigger: 'blur'}],
                num: [{required: true, message: '请输入商品数量', trigger: 'blur'}],
                admin_id: [{required: true, message: '请输入添加人', trigger: 'blur'}],
            },
            categoryList: [],
            statusList: [
                {
                    id: 1,
                    name: "上架"
                }, {
                    id: 0, name: '下架'
                }

            ],
            imageUrl: '',
            imageUrl1: '',
            bonusDialogVisible: false,
            bonusForm: {
                first: '',
                second: '',
                third: '',
                intermediate: '',
                senior: '',
                region: '',
                city: '',
                regions: '',
                global: '',
                a_type: {
                    first: 2, // 默认百分比
                    second: 2,
                    third: 2,
                    intermediate: 2,
                    senior: 2,
                    region: 2,
                    city: 2,
                    regions: 2,
                    global: 2,
                }
            },
            bonusFields: [
                { key: 'first', label: '第一个人', placeholder: '请输入分红' },
                { key: 'second', label: '第二个人', placeholder: '请输入分红' },
                { key: 'third', label: '第三个人', placeholder: '请输入分红' },
                { key: 'intermediate', label: '中级服务商', placeholder: '请输入分红' },
                { key: 'senior', label: '高级服务商', placeholder: '请输入分红' },
                { key: 'region', label: '区域服务商', placeholder: '请输入分红' },
                { key: 'city', label: '城市服务商', placeholder: '请输入分红' },
                { key: 'regions', label: '大区服务商', placeholder: '请输入分红' },
                { key: 'global', label: '全球服务商', placeholder: '请输入分红' },
            ],
            currentProductId: null, // 当前操作的商品ID
            currentProductInfo: null,
        };
    },
    mounted() {
        this.fetchAdminList();
        this.getCategory();
        setTimeout(_=>{
            this.showEdit();
        },1000)
    },
    computed: {
        ...mapState(["userInfo"]),
        dynamicEditorConfig() {
            const userInfo = localStorage.getItem("userInfo");
            let token = '';
            if (userInfo) {
                try {
                    const parsedUserInfo = JSON.parse(userInfo);
                    token = parsedUserInfo.token || '';
                    // Assign to data property if needed elsewhere, though computed should be sufficient
                    this.token = token;
                } catch (e) {
                    console.error("Failed to parse userInfo from localStorage", e);
                }
            }
            return {
                placeholder: '请输入商品描述...',
                MENU_CONF: {
                    uploadImage: {
                        server: '/admin/shop/imgUpload', // Using proxy path
                        fieldName: 'file',
                        headers: {
                            // Ensure the header name matches what the backend expects (e.g., Authorization or token)
                            token: token // Using 'token' as per previous config, adjust if backend expects 'Authorization'
                        },
                        // Custom insert logic
                        customInsert(res, insertFn) {
                            // res is the server response {state, code, msg, data: [...]}
                            if (res.code === 200 && res.data && res.data.length > 0) {
                                const relativeUrl = res.data[0];
                                // IMPORTANT: Construct the FULL URL for the image src
                                const fullUrl = (window.$appConfig ? window.$appConfig.imgPath : '') + relativeUrl;
                                // insertFn(url, alt, href)
                                insertFn(fullUrl, 'image', fullUrl); // Insert image with alt text and optional link
                            } else {
                                // Handle upload failure reported by the server
                                // You might want to use this.$message or similar here
                                console.error('Server reported upload error:', res.msg);
                                alert(`图片上传失败: ${res.msg}`); // Simple alert, replace with Element UI message if preferred
                            }
                        },
                        // Optional: Add more specific error handlers if needed
                        // onError(file, err, res) {
                        //    console.error('Upload network/config error', err);
                        //    alert(`图片上传出错: ${err.message}`);
                        // },
                        // onFailed(file, res) {
                        //     // This might overlap with customInsert's failure case depending on wangEditor version
                        //     console.error('Upload failed (onFailed)', res);
                        // }
                    },
                    codeSelectLang: [
                        { text: 'JavaScript', value: 'javascript' },
                        { text: 'HTML', value: 'html' },
                        { text: 'CSS', value: 'css' },
                        { text: 'Java', value: 'java' },
                        { text: 'Python', value: 'python' },
                        { text: 'C', value: 'c' },
                        { text: 'C++', value: 'cpp' },
                        { text: 'C#', value: 'csharp' },
                        { text: 'PHP', value: 'php' },
                        { text: 'Go', value: 'go' },
                        { text: 'Ruby', value: 'ruby' },
                        { text: 'Markdown', value: 'markdown' }
                    ]
                }
            };
        }
    },
    beforeDestroy() {
        this.handleDialogClose()
    },
    methods: {
        showEdit(){
            if(this.$route.query.id){
                const row = this.adminList.find(item => String(item.id) === String(this.$route.query.id));
                console.log()
                this.handleEdit(row)
            }
        },
        handleInput(value, key) {
            // 判断当前类型是百分比还是金额
            const type = this.bonusForm.a_type[key];
            let numValue = value.toString().replace(/[^\d.]/g, '');
            const decimalIndex = numValue.indexOf('.');
            if (decimalIndex !== -1) {
                numValue = numValue.substring(0, decimalIndex + 1) +
                    numValue.substring(decimalIndex + 1).replace(/\./g, '');
            }
            if (type === 2) { // 百分比
                // 只允许1-100的整数
                numValue = numValue.replace(/\..*$/, ''); // 移除小数点及后面
                let intValue = parseInt(numValue, 10);
                if (isNaN(intValue) || intValue < 1) {
                    intValue = '';
                } else if (intValue > 100) {
                    intValue = 100;
                }
                this.bonusForm[key] = intValue;
            } else { // 金额
                // 金额不做限制
                this.bonusForm[key] = numValue ? parseFloat(numValue) : '';
            }
        },
        handleEditEditorCreated(editor) {
            this.editEditor = editor;
            if (this.adminForm.content) {
                editor.setHtml(this.adminForm.content);
            }
        },
        handleAddEditorCreated(editor) {
            this.addEditor = editor;
        },
        // 对话框关闭时销毁编辑器
        handleDialogClose() {
            // 销毁编辑器实例
            if (this.addEditor) {
                this.addEditor.destroy();
                this.addEditor = null;
            }
            if (this.editEditor) {
                this.editEditor.destroy();
                this.editEditor = null;
            }

            // 保留图片数据
            this.detailImages = [];
        },
        getProductDetail(id) {
            return this.$http.get(`/admin/shop/edit`, {params: {id}}).then(result => {
                if (result.code === 200) {
                    return result.data;
                } else {
                    this.$message.error(result.msg);
                    return null;
                }
            });
        },
        handleCoverSuccess(res, file) {
            if (res.code === 200 && res.data) {
                try {
                    const imgPath = res.data;
                    this.adminForm.f_thumb = Array.isArray(imgPath) ? imgPath.join('') : imgPath;
                    this.$nextTick(() => {
                        this.$forceUpdate();
                    });
                    this.$message.success({
                        message: '封面图上传成功',
                        type: 'success',
                        duration: 1500
                    });
                } catch (error) {
                    console.error('处理封面图上传响应失败:', error);
                    this.$message.error('处理封面图数据失败');
                }
            } else {
                this.$message.error(res.msg || '封面图上传失败');
            }
        },
        beforeCoverUpload(file) {
            const isValidFormat = ['image/jpeg', 'image/png'].includes(file.type);
            const isLt20M = file.size / 1024 / 1024 < 20;

            if (!isValidFormat) {
                this.$message.error('封面图只能是 JPG/PNG 格式!');
                return false;
            }
            if (!isLt20M) {
                this.$message.error('封面图大小不能超过 20MB!');
                return false;
            }
            return true;
        },
        handleDetailSuccess(res, file) {
            if (res.code === 200 && res.data) {
                try {
                    const imgPath = res.data; // 获取相对路径
                    const currentImages = this.adminForm.thumb ? this.adminForm.thumb.split(',') : [];

                    if (!currentImages.includes(imgPath)) {
                        currentImages.push(imgPath);
                        this.adminForm.thumb = currentImages.join(',');
                        this.detailImages = currentImages.map(url => ({
                            url: this.$appConfig.imgPath + url,
                            name: url.split('/').pop() || 'detail_image'
                        }));
                    }
                    this.$message.success({
                        message: '详情图上传成功',
                        type: 'success',
                        duration: 1500
                    });
                } catch (error) {
                    console.error('处理详情图上传响应失败:', error);
                }
            } else {
                this.$message.error(res.msg || '详情图上传失败');
            }
        },
        beforeDetailUpload(file) {
            const isValidFormat = ['image/jpeg', 'image/png'].includes(file.type);
            const isLt20M = file.size / 1024 / 1024 < 20;

            if (!isValidFormat) {
                this.$message.error('详情图只能是 JPG/PNG 格式!');
                return false;
            }
            if (!isLt20M) {
                this.$message.error('详情图大小不能超过 20MB!');
                return false;
            }
            return true;
        },
        handleRemove(file) {
            try {
                // 获取当前保存的相对路径数组
                const currentImages = this.adminForm.thumb ? this.adminForm.thumb.split(',').filter(url => url.trim()) : [];

                // 确定要删除的相对路径
                let deleteUrl = '';
                if (file.response && file.response.data) { // 新上传的图片
                    deleteUrl = file.response.data;
                } else { // 已存在的图片
                    deleteUrl = file.url.replace(this.$appConfig.imgPath, '');
                }

                // 过滤出保留的图片
                const updatedImages = currentImages.filter(url => url !== deleteUrl);

                // 更新表单数据和显示列表
                this.adminForm.thumb = updatedImages.join(',');
                this.detailImages = updatedImages.map(url => ({
                    url: this.$appConfig.imgPath + url,
                    name: url.split('/').pop() || 'detail_image'
                }));

                this.$message.success({
                    message: '图片已删除',
                    type: 'success',
                    duration: 1500
                });
            } catch (error) {
                console.error('删除图片失败:', error);
                this.$message.error('删除图片失败，请重试');
            }
        },

        handlePreview(file) {
            this.previewImage = file.url;
            this.previewVisible = true;
        },
        getCategory() {
            const mergedParams = {
                page:1
            }
            this.$http.get('/admin/clas/lists', {params:mergedParams}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.categoryList = newListData;
                    this.total = result.data.total || newListData.length;
                }
            });
        },
        fetchAdminList() {
            const params = {
                page: this.currentPage,
                limit: this.pageSize
            };
            this.$http.get('/admin/shop/lists', {params}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    console.log(111111111111111111111,this.adminList)
                    this.total = result.data.total || newListData.length;
                }
            });
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchAdminList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList();
        },
        handleAddAdmin() {
            this.adminForm = {
                rebate:{
                    primary: '',
                    intermediate: '',
                    senior: '',
                    region: '',
                    city: '',
                    regions: '',
                    global: '',
                },
                is_recommend:0,
                title: '',
                clas_id: [],
                type: 1,
                description: '',
                thumb: '',
                f_thumb: '',
                content: '',
                state: 1,
                sort: '',
                pur_price: '',
                price: '',
                num: '',
                admin_id: '',
            };
            this.detailImages = []
            this.$refs.adminForm && this.$refs.adminForm.clearValidate();
            this.addDialogVisible = true;
            this.$nextTick(() => {
                if (this.editor) {
                    this.editor.setHtml('');
                }
            });
        },
        async handleEdit(row) {
            try {
                this.$message.info({
                    message: '正在加载商品信息...',
                    duration: 1000
                });

                const data = await this.getProductDetail(row.id);
                console.log('编辑商品返回数据:', data); // 加这一行
                if (data) {
                    // 处理图片数据
                    const thumbArray = (data.thumb || '').split(',').filter(url => url.trim());
                    this.detailImages = thumbArray.map(url => ({
                        url: this.$appConfig.imgPath + url, // 显示用完整URL
                        name: url.split('/').pop() || 'detail_image'
                    }));

                    // 处理分类回显：找到分类路径
                    let clasPath = this.findCategoryPath(this.categoryList, data.clas_id);
                    this.adminForm = {
                        ...data,
                        f_thumb: data.f_thumb || '',
                        thumb: data.thumb || '',
                        clas_id: clasPath.length ? clasPath : data.clas_id, // 兼容老数据
                        rebate: {
                            primary: '',
                            intermediate: '',
                            senior: '',
                            region: '',
                            city: '',
                            regions: '',
                            global: '',
                            ...(data.rebate || {})
                        }
                    };

                    this.$refs.adminForm && this.$refs.adminForm.clearValidate();
                    this.editDialogVisible = true;
                } else {
                    this.$message.error('未获取到商品数据');
                }
            } catch (error) {
                console.error('加载商品详情失败:', error);
                this.$message.error('加载商品详情失败，请重试');
            }
        },
        toSearch() {
            this.$http.get('/admin/shop/lists', {params: this.form, limit: 1}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        reset() {
            this.form = {}
            this.fetchAdminList()
        },
        handleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            this.$http.post('/admin/shop/del', {
                title: row.title,
                clas_id: row.clas_id,
                type: row.type,
                description: row.description,
                thumb: row.thumb,
                content: row.content,
                sort: row.sort,
                pur_price: row.pur_price,
                price: row.price,
                num: row.num,
                admin_id: row.admin_id,
                id: row.id,
                state: newState
            }).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },
        handleDelete(data) {
            this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message.info({
                    message: '正在删除...',
                    duration: 0,
                    showClose: true,
                    iconClass: 'el-icon-loading'
                });

                // 用户点击了确定按钮
                this.$http.post('/admin/shop/del', {
                    id: data.id,
                    state: "-1"
                }).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.fetchAdminList();
                    } else {
                        this.$message.error(result.msg);
                    }
                }).catch(error => {
                    console.error('删除商品失败:', error);
                    this.$message.error('删除商品失败，请重试');
                }).finally(() => {
                    // 关闭加载提示
                    this.$message.closeAll();
                });
            }).catch(() => {
                // 用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        submitForm() {
            this.$refs.adminForm.validate(valid => {
                if (valid) {
                    if (!this.adminForm.f_thumb) {
                        this.$message.warning('请上传商品封面图');
                        return;
                    }

                    this.$message.info({
                        message: '正在保存...',
                        duration: 0,
                        showClose: true,
                        iconClass: 'el-icon-loading'
                    });

                    // 只取最后一级分类id
                    let submitData = {
                        ...this.adminForm,
                        clas_id: Array.isArray(this.adminForm.clas_id) ? this.adminForm.clas_id[this.adminForm.clas_id.length - 1] : this.adminForm.clas_id
                    };

                    this.$http.post('/admin/shop/edit', submitData).then(result => {
                        if (result.code === 200) {
                            this.$message.success({
                                message: result.msg,
                                type: 'success',
                                duration: 1500
                            });
                            this.addDialogVisible = false;
                            this.editDialogVisible = false;
                            this.fetchAdminList();
                        } else {
                            this.$message.error(result.msg);
                        }
                    }).catch(error => {
                        console.error('保存商品失败:', error);
                        this.$message.error('保存商品失败，请重试');
                    }).finally(() => {
                        // 关闭加载提示
                        this.$message.closeAll();
                    });
                }
            });
        },
        // 递归查找分类路径
        findCategoryPath(list, id, path = []) {
            for (let item of list) {
                if (item.id === id) {
                    return [...path, item.id];
                }
                if (item.children && item.children.length) {
                    const found = this.findCategoryPath(item.children, id, [...path, item.id]);
                    if (found.length) return found;
                }
            }
            return [];
        },
        cancal(){
            this.bonusDialogVisible = false
            this.currentProductId = ""
            // 清空bonusFormIds对象，避免影响下次提交
            this.bonusFormIds = {}
            // 重置bonusForm
            this.bonusForm = {
                first: '',
                second: '',
                third: '',
                intermediate: '',
                senior: '',
                region: '',
                city: '',
                regions: '',
                global: '',
                a_type: {
                    first: 2,
                    second: 2,
                    third: 2,
                    intermediate: 2,
                    senior: 2,
                    region: 2,
                    city: 2,
                    regions: 2,
                    global: 2,
                }
            }
            this.currentProductInfo = null
        },
        async openBonusDialog(row) {
            try {
                this.$message.info({
                    message: '正在加载分红数据...',
                    duration: 1000
                });

                // 保存当前商品ID
                this.currentProductId = row.id;

                // 保存商品信息
                this.currentProductInfo = {
                    id: row.id,
                    title: row.title,
                    categoryName: row.categoryName || '', // 你可以根据 row.clas_id 去 categoryList 里查找名字
                    price: row.price
                };

                // 调用分红回显接口
                const result = await this.$http.get('/admin/shop/rebateEdit', {
                    params: { shop_id: row.id }
                });

                if (result.code === 200 && result.data) {
                    // 初始化默认值
                    this.bonusForm = {
                        first: '',
                        second: '',
                        third: '',
                        intermediate: '',
                        senior: '',
                        region: '',
                        city: '',
                        regions: '',
                        global: '',
                        a_type: {
                            first: 2, // 默认百分比
                            second: 2,
                            third: 2,
                            intermediate: 2,
                            senior: 2,
                            region: 2,
                            city: 2,
                            regions: 2,
                            global: 2,
                        }
                    };

                    // 处理回显数据
                    result.data.forEach(item => {
                        if (item.type && item.money !== undefined) {
                            this.bonusForm[item.type] = item.money;
                            this.bonusForm.a_type[item.type] = item.a_type || 2;
                            this.bonusFormIds[item.type] = item.id; // 保存id
                        }
                    });

                    this.bonusDialogVisible = true;
                } else {
                    this.$message.error(result.msg || '加载分红数据失败');
                }
            } catch (error) {
                console.error('加载分红数据失败:', error);
                this.$message.error('加载分红数据失败，请重试');
            }
        },
        submitBonus() {
            if ((this.bonusForm.first === undefined || this.bonusForm.first === null || this.bonusForm.first === '') ||
                (this.bonusForm.second === undefined || this.bonusForm.second === null || this.bonusForm.second === '') ||
                (this.bonusForm.third === undefined || this.bonusForm.third === null || this.bonusForm.third === '')) {
                // 显式排除 0 的情况
                if (this.bonusForm.first === 0 || this.bonusForm.second === 0 || this.bonusForm.third === 0) {
                    return; // 允许值为 0
                }
                this.$message.warning('第一个人、第二个人、第三个人为必填项');
                return;
            }
            // 所有分红项都要传，未填写的传空字符串，id只在有时传
            const keys = ['first', 'second', 'third', 'intermediate', 'senior', 'region', 'city', 'regions', 'global'];
            const rebateData = keys.map(key => {
                const obj = {
                    item: key,
                    val: this.bonusForm[key] !== undefined ? this.bonusForm[key] : '',
                    a_type: this.bonusForm.a_type && this.bonusForm.a_type[key] ? this.bonusForm.a_type[key] : 2
                };
                if (this.bonusFormIds && this.bonusFormIds[key]) {
                    obj.id = this.bonusFormIds[key];
                }
                return obj;
            });

            // 构建提交数据
            const submitData = {
                shop_id: this.currentProductId,
                rebate: JSON.stringify(rebateData)
            };

            // 提交到后端
            this.$http.post('/admin/shop/rebateEdit', submitData).then(result => {
                if (result.code === 200) {
                    this.$message.success('分红金额设置成功');
                    this.bonusDialogVisible = false;
                    // 清空bonusFormIds对象
                    this.bonusFormIds = {}
                    // 重置表单数据
                    this.bonusForm = {
                        first: '',
                        second: '',
                        third: '',
                        intermediate: '',
                        senior: '',
                        region: '',
                        city: '',
                        regions: '',
                        global: '',
                        a_type: {
                            first: 2,
                            second: 2,
                            third: 2,
                            intermediate: 2,
                            senior: 2,
                            region: 2,
                            city: 2,
                            regions: 2,
                            global: 2,
                        }
                    }
                    this.currentProductId = ""
                    this.currentProductInfo = null
                    // 刷新商品列表
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '分红金额设置失败');
                }
            }).catch(error => {
                console.error('设置分红金额失败:', error);
                this.$message.error('设置分红金额失败，请重试');
            });
        },
    }
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
    box-shadow: 0 0 8px rgba(64, 158, 255, 0.4);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    transition: all 0.3s;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
    border-radius: 6px;
}

/* 详情图上传样式 */
.detail-uploader /deep/ .el-upload--picture-card {
    transition: all 0.3s;

    &:hover {
        border-color: #409EFF;
        box-shadow: 0 0 8px rgba(64, 158, 255, 0.4);
    }
}

.detail-uploader /deep/ .el-upload-list--picture-card .el-upload-list__item {
    transition: all 0.3s;

    &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
}

/* 预览图片样式 */
.preview-dialog {
    /deep/ .el-dialog__body {
        padding: 10px;
        text-align: center;
    }

    .preview-image {
        max-width: 100%;
        max-height: 70vh;
    }
}

.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #f0f2f5;

        .header-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
    }

    .table-header {
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
        }

        .table-actions {
            .el-button {
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }

    .el-tabs {
        margin-top: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 28px;
            border-bottom: 2px solid #f0f2f5;
        }

        :deep(.el-tabs__item) {
            font-size: 15px;
            padding: 0 28px;
            height: 44px;
            line-height: 44px;
            transition: all 0.3s;

            &.is-active {
                color: #2563eb;
                font-weight: 500;
            }

            &:hover {
                color: #2563eb;
            }
        }

        :deep(.el-tabs__active-bar) {
            height: 2px;
            background-color: #2563eb;
            transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        }
    }

    .el-table {
        margin-top: 12px;
        border-radius: 8px;
        overflow: hidden;

        :deep(th) {
            background-color: #f9fafb !important;
            font-weight: 500;
            color: #4b5563;
        }

        :deep(td) {
            padding: 12px 0;
        }

        .delete-btn {
            color: #dc2626;
            transition: all 0.3s;

            &:hover {
                color: #ef4444;
            }
        }
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    /deep/ .el-dialog__header {
        text-align: center !important;
        padding: 16px;
    }

    .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        max-height: 90vh;
        display: flex;
        flex-direction: column;

        :deep(.el-dialog__header) {
            padding: 20px 24px !important;
            border-bottom: 1px solid #f0f2f5;
            margin: 0;

            .el-dialog__title {
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }
        }

        :deep(.el-dialog__body) {
            padding: 32px 24px;
            flex: 1;
            overflow-y: auto;

            .el-form-item {
                .el-input,
                .el-select {
                    width: 320px;
                }
            }
        }

        :deep(.el-tree) {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            padding: 10px;
        }

        :deep(.el-dialog__footer) {
            padding: 16px 24px;
            border-top: 1px solid #f0f2f5;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #374151;
        }

        :deep(.el-button) {
            padding: 8px 20px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-1px);
            }
        }
    }
}

.editor-container {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding: 5px;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 10px;
    width: 90%;
}

.ellipsis-column.el-table__cell span {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
    word-break: keep-all; /* 防止中文单词被截断 */
}

.tip-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
}

/* 分红金额弹窗样式 */
.bonus-dialog {
    /deep/ .el-form-item {
        margin-bottom: 16px;
    }

    /deep/ .el-input {
        .el-input__inner {
            border-radius: 4px;
        }
    }

    /deep/ .el-select {
        .el-input__inner {
            border-radius: 4px;
        }
    }
}

/deep/ .el-tab-pane {
    height: 650px;
    overflow-y: auto;
}

.bonus-product-info {
    padding: 10px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 16px;
}

</style>


